package com.wmyg.antifake.wxpay;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConfig;
import com.github.wxpay.sdk.WXPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 王卓逸
 * @program TODO
 * @description TODO
 * @create 2019-05-21
 */
@Slf4j
public class MiaomarkWxConfig implements WXPayConfig {

    private byte[] certData;

    public MiaomarkWxConfig() throws Exception {
        String certPath = "/mnt/wxpaycert/apiclient_cert.p12";
        File file = new File(certPath);
        InputStream certStream = new FileInputStream(file);
        this.certData = new byte[(int) file.length()];
        certStream.read(this.certData);
        certStream.close();
    }

    private Boolean isSandBox;

    private String appid = "wx770a614719630138";

    private String mchid = "1504988891";

    private String key = "wmyglk09SRT90rJH7896KY7qw09erD89";

    @Override
    public String getAppID() {
        return appid;
    }

    @Override
    public String getMchID() {
        return mchid;
    }

    @Override
    public String getKey() {
        return key;
    }

    @Override
    public InputStream getCertStream() {
        ByteArrayInputStream certBis = new ByteArrayInputStream(this.certData);
        return certBis;
    }

    @Override
    public int getHttpConnectTimeoutMs() {
        return 8000;
    }

    @Override
    public int getHttpReadTimeoutMs() {
        return 10000;
    }

    public void retrieveSandboxSignKey(WXPay wxPay) {
        try {
            Map<String, String> params = new HashMap<>();
            params.put("mch_id", this.mchid);
            params.put("nonce_str", WXPayUtil.generateNonceStr());
            params.put("sign", WXPayUtil.generateSignature(params, this.key));
            String strXML = wxPay.requestWithoutCert("https://api.mch.weixin.qq.com/sandboxnew/pay/getsignkey", params, 8000, 10000);
            if (StringUtils.isNotBlank(strXML)) {

                Map<String, String> result = WXPayUtil.xmlToMap(strXML);
                log.info("retrieveSandboxSignKey:{}", result);
                if ("SUCCESS".equals(result.get("return_code"))) {
                    this.key = result.get("sandbox_signkey");
                }
            } else {
                log.warn("The response is blank");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
